package com.lnj.community.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.lnj.community.annotation.LoginRequired;
import com.lnj.community.utiles.CommunityUtil;
import com.lnj.community.utiles.HostHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 拦截器
     * @param request
     * @param response
     * @param handler 拦截的目标对象 就是controller对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断拦截的目标对象是否需要拦截
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //判断方法是否有LoginRequired注解
            LoginRequired loginRequired = handlerMethod.getMethodAnnotation(LoginRequired.class);
            if (loginRequired != null && HostHolder.getUser() == null){
                // 判断是否是 AJAX 请求
                if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                    //返回应该JSON格式的数据
                    response.setContentType("application/json;charset=utf-8");
                    //返回数据
                    response.getWriter().print(CommunityUtil.getJSONString(302,"未登录,跳转到登录页面"));
                } else {
                    String redirectUrl = request.getContextPath() + "/login";
                    response.sendRedirect(redirectUrl);
                }
                return false;
            }
        }
        return true;
    }
}
